/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-06-10 15:02:14
 * @LastEditors: jqm123 2289662078@qq.com
 * @LastEditTime: 2025-08-21 15:18:01
 * @FilePath: /anxinxiu/src/utils/request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from "axios";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { Toast } from "vant";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 300000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.token) {
      // please modify it according to the actual situation
      config.headers["token"] = getToken();
    }
    if (config.proxyMode) {
      config.baseURL = config.proxyMode;
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Toast.fail(res.message || "Error");
      return Promise.reject(res.message);
    } else {
      return res.result;
    }
  },
  (error) => {
    if (error.response || error.message.cancel) {
      switch (error.response.status) {
        case 401:
          // Toast.fail("会话过期，请重新登录！");
          setTimeout(() => {
            window.location.href = error.response.headers.redirecturl;
          }, 2200);
          return;
      }
    } else {
      Toast.fail(error.message);
    }
    return Promise.reject(error);
  }
);

export function get(url, params, baseURL) {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params: params,
        baseURL: baseURL ? baseURL : process.env.VUE_APP_BASE_API,
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        // console.log(' get err:', err)
        reject(err);
      });
  });
}

export function post(url, data) {
  // console.log(contentType ? contentType : 'application/json')
  return new Promise((resolve, reject) => {
    service
      .post(url, data)
      // .then((res) => checkLogin(res))
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        // console.log(' post err res:', err)
        reject(err);
      });
  });
}

export default service;
